<template>
  <div class="home">
    <span>{{ liteFlowData }}</span>
    <div ref="container" class="container"></div>
  </div>
</template>
<script setup lang="ts">
import {ref, onMounted, toRaw} from 'vue';
import LogicFlow from "@logicflow/core";
import "@logicflow/core/dist/style/index.css";
import '@logicflow/extension/lib/style/index.css'

import {DndPanel, SelectionSelect, Menu} from '@logicflow/extension';

import CommonNode from "./common/CommonNode"
import SwitchNode from "./switch/SwitchNode"
import IFNode from "./if/IfNode"
import LoopNode from "./loop/LoopNode";
import {GraphConfigData} from '@logicflow/core';
import MyParse from "../parse/MyParse";


// 声明容器的对应ref对象和LF对象
const container = ref();
const lf = ref<LogicFlow>();
const liteFlowData = ref("");

//作为id
const getId = (): string => {
  const index = Number(localStorage.getItem("index") as string) + 1;
  localStorage.setItem("index", "" + index);
  return "n" + index;
}
if (!localStorage.getItem("index")) localStorage.setItem("index", "0");

onMounted(() => {

  lf.value = new LogicFlow({
    container: container.value,
    grid: true,
    plugins: [DndPanel, SelectionSelect, Menu],
  })

  lf.value.extension.dndPanel.setPatternItems([{
    type: 'Html',
    text: '',
    label: 'common',
    icon: '',

  }, {
    type: 'IF',
    text: '',
    label: 'if',
    icon: '',

  }, {
    type: 'SWITCH',
    text: '',
    label: 'switch',
    icon: '',

  }, {
    type: 'LOOP',
    text: '',
    label: 'loop',
    icon: '',

  }]);
  lf.value.extension.selectionSelect.openSelectionSelect();

  //注册自定义html节点
  lf.value.register(CommonNode)
  lf.value.register(SwitchNode)
  lf.value.register(LoopNode)
  lf.value.register(IFNode)

  const onChange = () => {
    const data = lf.value?.getGraphRawData() as GraphConfigData
    localStorage.setItem("data", JSON.stringify(data));
    const parse = new MyParse(data);
    const node = parse.parse();
    liteFlowData.value = node.getElString();
  }

  //监听画布变化，触发change方法
  lf.value.on('history:change', onChange);

  //监听拖入节点，修改id方便展示
  lf.value.on('node:dnd-add', (data) => {
    const node = data.data;
    lf.value?.deleteNode(node.id);

    node.id = getId()
    lf.value?.addNode(node);
  })

  const data = JSON.parse(localStorage.getItem("data") as string) as GraphConfigData;
  toRaw(lf.value).render(data)

  onChange();
})

</script>
<style>
.home {
  width: 100%;
  height: 99vh;
  display: flex;
  flex-direction: column;
}

.container {
  flex: 1;
}
</style>